/*******************************************************************************
 * Copyright (c) Jonathan Buck - jonbuck16@gmail.com
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    jonbuck16@gmail.com - initial API and implementation
 *******************************************************************************/
package net.jonbuck.tassoo.ui.view.dnd;

import net.jonbuck.tassoo.model.Container;
import net.jonbuck.tassoo.model.Task;
import net.jonbuck.tassoo.model.TassooPackage;
import net.jonbuck.tassoo.persistence.dao.TassooDao;
import net.jonbuck.tassoo.persistence.dao.TassooDaoImpl;
import net.jonbuck.tassoo.persistence.dao.util.TassooDaoHelperUtil;

import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TransferData;

/**
 * 
 * 
 * @since 1.0.0
 */
public class TasksViewDropListener extends ViewerDropAdapter {

	private Container container;

	private TassooDao tassooDao = TassooDaoImpl.getInstance();

	private Task source;

	private int location;

	private Task target;

	private AdapterFactoryEditingDomain editingDomain;

	/**
	 * 
	 * @param viewer
	 */
	public TasksViewDropListener(Viewer viewer) {
		super(viewer);
		editingDomain = tassooDao.getEditingDomain();
	}

	/**
	 * 
	 */
	public boolean performDrop(Object data) {
		decodeData(data.toString());
		switch (location) {
		case 1: // Dropped before the target

		case 2: // Dropped after the target

		case 3: // Dropped on the target object
			editingDomain.getCommandStack().execute(
					AddCommand.create(editingDomain, target, TassooPackage.Literals.TASK__TASK, source));
			break;
		case 4: // Dropped into space
			editingDomain.getCommandStack().execute(
					AddCommand.create(editingDomain, container, TassooPackage.Literals.CONTAINER__TASK, source));
			break;
		}
		return true;
	}

	/**
	 * 
	 * @param string
	 */
	private void decodeData(String string) {
		String[] sourceData = StringUtils.split(string, "~");
		this.container = TassooDaoHelperUtil.getContainerByValue(tassooDao, sourceData[0]);
		this.source = TassooDaoHelperUtil.getTaskByValue(tassooDao, container, sourceData[1]);
	}

	/**
	 * 
	 */
	public void drop(DropTargetEvent event) {
		location = this.determineLocation(event);
		target = (Task) determineTarget(event);
		super.drop(event);
	}

	/**
	 * 
	 */
	public boolean validateDrop(Object target, int operation, TransferData transferType) {
		return true;
	}

}
